<template>
  <!-- 附件批量查看 -->
  <div>
    <el-popover
      :placement="placement"
      :title="title"
      :width="width"
      :trigger="trigger"
      @show="show"
    >
      <template #reference>
        <el-button type="primary" link>View</el-button>
      </template>
      <el-skeleton :loading="skeleton" :rows="3" animated :throttle="1000">
        <template #default>
          <ul class="root" v-if="fileList?.length">
            <li v-for="(item, index) in fileList" :key="index">
              <!-- <i :class="getIcon(item)"></i> -->
              <img :src="getIcon(item)" />
              <span class="file_name_warp">{{ item.name }}</span>
              <img
                class="file_action_wrap"
                src="@/assets/image/Preview.png"
                @click="viewFile(item)"
              />
            </li>
          </ul>
          <p v-else class="no_data">No Data</p>
        </template>
      </el-skeleton>
    </el-popover>
  </div>
</template>

<script setup>
import _ from 'lodash';
import { apiMethods } from '@/utils/http.js';
import { ElMessage } from 'element-plus';
const attrs = useAttrs();
// const route = useRouter();

const imageFormat = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'pct', 'raw', 'tga', 'tif', 'psd', 'webp'];

const emits = defineEmits(['itemEvent']);
import pdf from '@/assets/image/Pdf.png';
import excel from '@/assets/image/Excel.png';
import photo from '@/assets/image/Photo.png';
import file from '@/assets/image/File.png';
import { nextTick } from 'vue';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  placement: {
    type: String,
    default: 'bottom-end',
  },
  title: {
    type: String,
    default: 'Attachment',
  },
  width: {
    type: Number,
    default: 300,
  },
  trigger: {
    type: String,
    default: 'click',
  },
  row: {
    type: Object,
    default: () => ({}),
  },
  filterKey: {
    type: Object,
    default: {
      name: 'name',
      url: 'url',
    },
  },
  requestUrl: {
    // 如果传入url 请求接口后渲染附件列表
    type: String,
    default: '',
  },
  requestParams: {
    type: Object,
    default: () => {},
  },
});

let fileList = ref([]);
const skeleton = ref(true);

const show = () => {
  if (props.requestUrl) {
    getRequestList();
  }
};

const getRequestList = async () => {
  skeleton.value = true;
  try {
    let res = await apiMethods.post(props.requestUrl, {
      ...props.requestParams,
    });
    res.data.data.forEach(item => {
      item.name = item[props.filterKey.name];
      item.url = item[props.filterKey.url];
    });
    fileList.value = res.data.data;
    skeleton.value = false;
  } catch (error) {
    fileList.value = [];
    skeleton.value = false;
  }
};

function getIcon(item) {
  let fileSuffix = item?.name?.substring(item.name.lastIndexOf('.') + 1);
  fileSuffix = fileSuffix?.toLowerCase(); // 转小写匹配
  if (imageFormat.indexOf(fileSuffix) > -1) {
    return photo;
  } else if (fileSuffix === 'pdf') {
    return pdf;
  } else if (fileSuffix === 'xls' || fileSuffix === 'xlsx') {
    return excel;
  } else {
    return file;
  }
}

function viewFile(item) {
  let params = null;
  let uid = item.uid || item?.raw?.uid;
  if (item.url) {
    // 列表或者详情接口有返回url地址
    params = encodeURIComponent(
      JSON.stringify({
        url: item.url,
        name: item.name,
      })
    );
    let fileSuffix = item?.name?.substring(item.name.lastIndexOf('.') + 1);
    fileSuffix = fileSuffix?.toLowerCase(); // 转小写匹配
    if (imageFormat.indexOf(fileSuffix) > -1) fileSuffix = 'image';
    emits('itemEvent', {
      ...attrs,
      ...item,
      fileParams: params,
      params,
      component: 'viewFile',
      fileSuffix,
    });
  } else {
    uid ? '' : ElMessage.warning('No attachment address found');
  }
}
</script>
<style lang="scss" scoped>
.no_data {
  text-align: center;
  padding: 0;
  margin: 0;
}
.root {
  max-height: 300px;
  overflow-y: auto;
  li {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    background: #f8fafb;
    padding: 3px 6px;
    box-sizing: border-box;
    margin-bottom: 10px;

    .file_name_warp {
      flex: 1;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //用省略号显示
      white-space: nowrap; //不换行
      margin-left: 6px;
    }
    .file_action_wrap {
      cursor: pointer;
      margin-left: 6px;
    }
  }
}
</style>
